import React, { Component } from 'react';
import { Button, Grid, Message, Select, NumberPicker } from '@alifd/next';
import IceContainer from '@icedesign/container';
import webStorageCache from 'web-storage-cache';
import { MODE_COM, MODE_MQTT, host } from '../../../../const';
import request from '../../../../utils/request';


const wsCache = new webStorageCache();
const { Row, Col } = Grid;

export default class ProtocolSetForm extends Component {
  static displayName = 'ProtocolSetForm';

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
      super(props);
      this.state = {
          protocol: '',
          isTestLoading: false,
          com: {},
          isComWorking: false,
          comV: {},
          isComVWorking: false,
          comDataSource: {},
          vBaudRate: 38400,
      };
      this.handleChange = this.handleChange.bind(this);
      this.changeProtocol = this.changeProtocol.bind(this);
      this.testMqtt = this.testMqtt.bind(this);
  }


  componentDidMount() {
      this.init();


      request({
        method: 'GET',
        url: `${host}/serialPort/list`,
    }).then((res) => {
        const data = res?.data?.data;
        const code = res?.data?.code;
        if (code === 200) {
            const dataSource = new Array();
            data.forEach((com) => {
                const item = {};
                item.value = com;
                dataSource.push(item);
            });
            this.setState({
                comDataSource: dataSource,
            });
        }
    });
    this.updateComStatus();
    this.updateComVStatus();
  }

  init() {
      const lProtocol = wsCache.get('protocol');
      if (lProtocol) {
          this.setState({
              protocol: lProtocol,
          });
      }
  }
  handleChange(val) {
      this.setState({
          protocol: val,
      });
  }
  changeProtocol() {
      if (!this.state.protocol) {
          Message.error('请选择通讯模式!');
          return;
      }
      wsCache.set('protocol', this.state.protocol);
      Message.success('通讯模式设置成功');
  }
  testMqtt() {
      this.setState({
          isTestLoading: true,
      });
      request({
          method: 'GET',
          url: `${host}/mqtt/test`,
      }).then(({ data }) => {
          this.setState({
              isTestLoading: false,
          });
          if (data.code === 200) {
              Message.success(data?.msg);
          }
      }, () => {
          this.setState({
              isTestLoading: false,
          });
      });
  }
  
  updateComStatus() {
    request({
        method: 'GET',
        url: `${host}/serialPort`,
    }).then((res) => {
        const data = res?.data?.data;
        const code = res?.data?.code;
        if (code === 200) {
            if (data == null) {
                this.setState({
                    com: {},
                    isComWorking: false,
                });
            } else if (data.status == 0) {
                this.setState({
                    com: data,
                    isComWorking: true,
                });
                Message.success('天线设备连接成功');
            } else if (data.status == 1) {
                this.setState({
                    com: {},
                    isComWorking: false,
                });
            }
        }
    });
}
updateComVStatus() {
    request({
        method: 'GET',
        url: `${host}/serialPort/indoor`,
    }).then((res) => {
        const data = res?.data?.data;
        const code = res?.data?.code;
        if (code === 200) {
            if (data == null) {
                this.setState({
                    comV: {},
                    isComVWorking: false,
                });
            } else if (data.status == 0) {
                const portName = data.portName;
                this.setState({
                    comV: {
                        innnerPortName: portName,
                    },
                    isComVWorking: true,
                });
                Message.success('天线设备连接成功');
            } else if (data.status == 1) {
                this.setState({
                    comV: {},
                    isComVWorking: false,
                });
            }
        }
    });
}

componentDidMount() {
   
}

handlePortNameChange=(value) => {
    this.setState({
        com: {
            portName: value,
        },
    });
}
handleInnerPortNameChange=(value) => {
    console.log('测试111 ~ file: index.jsx ~ line 116 ~ ComSettingForm ~ value', value);
    this.setState({
        comV: {
            innnerPortName: value,
        },
    });
}

openPort=() => {
    request({
        method: 'GET',
        url: `${host}/serialPort/open`,
        params: {
            portName: this.state.com.portName,
            baudRate: 38400,
        },
    }).then(() => {
        this.updateComStatus();
    });
}
openVPort=() => {
    if (!this.state.vBaudRate) {
        Message.error('请输入波特率');
        return;
    }
    request({
        method: 'GET',
        url: `${host}/serialPort/indoor/open`,
        params: {
            portName: this.state.comV.innnerPortName,
            baudRate: this.state.vBaudRate,
        },
    }).then(() => {
        this.updateComVStatus();
    });
}

closePort=() => {
    request({
        method: 'GET',
        url: `${host}/serialPort/close`,
    }).then(() => {
        this.updateComStatus();
    });
}
closeVPort=() => {
    request({
        method: 'GET',
        url: `${host}/serialPort/indoor/close`,
    }).then(() => {
        this.updateComVStatus();
    });
}

  render() {
      return (
          <div className="private-message-form">
              <IceContainer title="通讯配置">
                  <Row style={{ marginBottom: '20px' }}>
                      <Col xxs="5" s="5" l="2">
              通讯模式
                      </Col>
                      <Col s="14" l="7">

                          <Select
                              style={{ width: 200 }}
                              value={this.state.protocol}
                              onChange={this.handleChange}
                          >
                              <Select.Option value={MODE_COM} >普通模式</Select.Option>
                              <Select.Option value={MODE_MQTT} >4G模式</Select.Option>
                          </Select>

                      </Col>
                  </Row>
                  {
                      this.state.protocol === MODE_MQTT ? <Row style={{ marginBottom: '20px' }}>
                          <Col xxs="5" s="5" l="2">
                              {' '}
                          </Col>
                          <Col>


                              <Button type="primary" loading={this.state.isTestLoading} onClick={this.testMqtt} >
                      测试MQTT连接
                              </Button>

                          </Col>
                      </Row> : null
                  }


                  <Row style={{ marginBottom: '20px' }}>
                      <Col xxs="5" s="5" l="2">
                          {' '}
                      </Col>
                      <Col>
                          <Button type="primary" onClick={this.changeProtocol} >
                修改
                          </Button>
                      </Col>
                  </Row>

{
    this.state.protocol === MODE_COM?
   <>
      <Row style={{ marginBottom: '20px' }}>
                      <Col xxs="5" s="5" l="2">
              室外天线接口
                      </Col>
                      <Col s="14" l="7">

                          <Select
                              style={{ width: 200 }}
                              dataSource={this.state.comDataSource}
                              value={this.state.com.portName}
                              onChange={this.handlePortNameChange}
                              disabled={this.state.isComWorking}
                          />

                      </Col>
                  </Row>


                  <Row>
                      <Col xxs="5" s="5" l="2">
                          {' '}
                      </Col>
                      <Col>
                          <Button type="primary" onClick={this.openPort} disabled={this.state.isComWorking}>
                连接
                          </Button>
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                          <Button type="primary" onClick={this.closePort} disabled={!this.state.isComWorking}>
                断开
                          </Button>
                      </Col>
                  </Row>
                  <Row>
                      <Col > &nbsp; </Col>
                  </Row>
                  <Row style={{ marginBottom: '20px' }}>
                      <Col xxs="5" s="5" l="2">
              室内天线接口
                      </Col>
                      <Col >

                          <Select
                              style={{ width: 200 }}
                              dataSource={this.state.comDataSource}
                              value={this.state.comV.innnerPortName}
                              onChange={this.handleInnerPortNameChange}
                              disabled={this.state.isComVWorking}
                          />

                      </Col>
                      <Col />
                  </Row>
                  <Row style={{ marginBottom: '20px' }}>
                      <Col xxs="5" s="5" l="2">
              波特率
                      </Col>
                      <Col >


                          <NumberPicker
                              placeholder="波特率"
                              disabled={this.state.isComVWorking}
                              value={this.state.vBaudRate}
                              onChange={(val) => {
                                  this.setState({
                                      vBaudRate: val,
                                  });
                              }}
                          />
                      </Col>
                      <Col />
                  </Row>


                  <Row>
                      <Col xxs="5" s="5" l="2">
                          {' '}
                      </Col>
                      <Col>
                          <Button type="primary" onClick={this.openVPort} disabled={this.state.isComVWorking}>
                连接
                          </Button>
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                          <Button type="primary" onClick={this.closeVPort} disabled={!this.state.isComVWorking}>
                断开
                          </Button>
                      </Col>
                  </Row>
             
   </>
    :null
}

              </IceContainer>
          </div>
      );
  }
}

